package com.example.project10;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
//george.bluth@reqres.in
//新密码123456
//pistol
public class LoginActivity extends AppCompatActivity {

    private static final int LOGIN_SUCCESS = 1;
    private static final int LOGIN_FAILED = 0;
    private static final int LOGIN_START = 2;
    private static final int REGISTER_REQUEST_CODE = 1001;

    private EditText editTextUsername;
    private EditText editTextPassword;
    private CheckBox checkboxAgreement;
    private CheckBox checkboxAutoLogin;
    private Button buttonLogin;
    private TextView tvRegister;
    private ProgressBar progressBar;
    private ImageView ivPasswordToggle;
    private boolean isPasswordVisible = false;

    private LoginViewModel loginViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // 检查自动登录
        if (shouldAutoLogin()) {
            // 显示启动画面并执行自动登录
            showLoadingScreen();
            performAutoLogin();
            return;
        }
        
        setContentView(R.layout.activity_login);

        initViews();
        setupListeners();
        
        // 初始化ViewModel
        loginViewModel = new ViewModelProvider(this).get(LoginViewModel.class);
        observeViewModel();
    }

    private void initViews() {
        // ID 已经和 activity_login.xml 完全对应
        editTextUsername = findViewById(R.id.editText_username);
        editTextPassword = findViewById(R.id.editText_password);
        checkboxAgreement = findViewById(R.id.checkbox_agreement);
        checkboxAutoLogin = findViewById(R.id.checkbox_auto_login);
        buttonLogin = findViewById(R.id.button_login);
        tvRegister = findViewById(R.id.tv_register);
        progressBar = findViewById(R.id.progressBar);
        ivPasswordToggle = findViewById(R.id.iv_password_toggle);
    }

    private void setupListeners() {
        editTextUsername.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                editTextUsername.setText(editTextUsername.getText().toString().trim());
            }
        });

        checkboxAgreement.setOnCheckedChangeListener((buttonView, isChecked) -> {
            buttonLogin.setEnabled(isChecked);
        });

        buttonLogin.setOnClickListener(v -> {
            final String username = editTextUsername.getText().toString().trim();
            final String password = editTextPassword.getText().toString().trim();
            final boolean autoLogin = checkboxAutoLogin.isChecked();
            
            if (username.isEmpty()) {
                Toast.makeText(LoginActivity.this, "请输入邮箱", Toast.LENGTH_SHORT).show();
                return;
            }
            if (password.isEmpty()) {
                Toast.makeText(LoginActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
                return;
            }
            if (!checkboxAgreement.isChecked()) {
                Toast.makeText(LoginActivity.this, "请同意用户协议", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 执行登录
            loginViewModel.login(username, password, autoLogin);
        });

        tvRegister.setOnClickListener(v -> {
            // 跳转到注册页面
            Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
            startActivityForResult(intent, REGISTER_REQUEST_CODE);
        });

        ivPasswordToggle.setOnClickListener(v -> {
            isPasswordVisible = !isPasswordVisible;
            if (isPasswordVisible) {
                editTextPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                ivPasswordToggle.setImageResource(R.drawable.ic_eye_visible); // 更换为"睁眼"图标
            } else {
                editTextPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                ivPasswordToggle.setImageResource(R.drawable.ic_eye_hidden); // 更换为"闭眼"图标
            }
            editTextPassword.setSelection(editTextPassword.getText().length());
        });
    }

    private void observeViewModel() {
        loginViewModel.isLoading.observe(this, isLoading -> {
            if (isLoading != null) {
                if (isLoading) {
                    progressBar.setVisibility(View.VISIBLE);
                    buttonLogin.setEnabled(false);
                } else {
                    progressBar.setVisibility(View.GONE);
                    buttonLogin.setEnabled(checkboxAgreement.isChecked());
                }
            }
        });

        loginViewModel.loginResult.observe(this, result -> {
            if (result != null) {
                if (result.equals("SUCCESS")) {
                    Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                    navigateToMain();
                } else if (result.startsWith("ERROR: ")) {
                    String errorMessage = result.substring(7); // 移除"ERROR: "前缀
                    Toast.makeText(LoginActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
                }
            }
        });

        loginViewModel.registerResult.observe(this, result -> {
            if (result != null) {
                if (result.equals("SUCCESS")) {
                    Toast.makeText(LoginActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                    navigateToMain();
                } else if (result.startsWith("ERROR: ")) {
                    String errorMessage = result.substring(7); // 移除"ERROR: "前缀
                    Toast.makeText(LoginActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
                }
            }
        });

        loginViewModel.autoLoginResult.observe(this, result -> {
            if (result != null) {
                if (result.equals("SUCCESS")) {
                    Toast.makeText(LoginActivity.this, "自动登录成功", Toast.LENGTH_SHORT).show();
                    navigateToMain();
                } else if (result.startsWith("ERROR: ")) {
                    // 自动登录失败，显示登录页面
                    hideLoadingScreen();
                    setContentView(R.layout.activity_login);
                    initViews();
                    setupListeners();
                    loginViewModel = new ViewModelProvider(this).get(LoginViewModel.class);
                    observeViewModel();
                    
                    String errorMessage = result.substring(7); // 移除"ERROR: "前缀
                    Toast.makeText(LoginActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void navigateToMain() {
        String username = editTextUsername.getText().toString().trim();
        String userEmail = username.isEmpty() ? "user@example.com" : username;
        
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        intent.putExtra("user_email", userEmail);
        startActivity(intent);
        finish();
    }

    private boolean shouldAutoLogin() {
        return SharedPreferencesUtil.isAutoLoginEnabled(this) && 
               SharedPreferencesUtil.getToken(this) != null;
    }

    private void showLoadingScreen() {
        setContentView(R.layout.activity_login);
        progressBar.setVisibility(View.VISIBLE);
        Toast.makeText(this, "自动登录中...", Toast.LENGTH_SHORT).show();
    }

    private void hideLoadingScreen() {
        progressBar.setVisibility(View.GONE);
    }

    private void performAutoLogin() {
        loginViewModel = new ViewModelProvider(this).get(LoginViewModel.class);
        observeViewModel();
        loginViewModel.autoLogin();
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (requestCode == REGISTER_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            // 注册成功，获取返回的邮箱信息并填充到登录页面
            String email = data.getStringExtra("email");
            if (email != null) {
                editTextUsername.setText(email);
                // 自动勾选用户协议
                checkboxAgreement.setChecked(true);
                Toast.makeText(this, "注册成功，请登录", Toast.LENGTH_SHORT).show();
            }
        }
    }
}